package vendingmachine

import org.codehaus.groovy.grails.commons.*

import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Locale
import grails.converters.JSON
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import biz.base64Coder.Base64Coder
import java.net.URLDecoder
import net.iasolution.jpay.server.util.URIUtil
import net.iasolution.vendingmachine.constance.*

class UserProcessController {

    def index() {
		[] 
	}
	
	def posterService
    
    def registerFromFacebook() {
        if(params.signed_request!=null){
            def singed_info = params.signed_request.split("\\.")
			def sign = null
            def payload = new String(singed_info[1].replace('-_', '+/').decodeBase64())

            def jpayload = JSON.parse(payload)
			def u =null
			if(isValidInfo(jpayload,sign)){
				if(ShiroUser.findByFacebookId(jpayload.user_id)==null){
					def data = jpayload.registration
					u = new ShiroUser(username:data?.name , 
							              passwordHash: "" ,
										  authToken : jpayload.oauth_token,
										  email:data?.email,
										  facebookId :  jpayload.user_id,
										  cardId :  data?.cardId,
										  gender : data?.gender
					)
					u.addToRoles(ShiroRole.findByName(VendingConstance.ROLE_USER))
					u.save()
					if(u.hasErrors()){
						u.errors.each { println "eeee : ${it}" } 
					}else
						posterService.postResult(u.cardId)
					
				}else
					u = ShiroUser.findByFacebookId(jpayload.user_id)
			}
			session.user = u
			
			redirect(url:VendingConstance.FACEBOOK_APP_URL)
			//redirect(controller:"information",action:"main")
        }
    }
    
    private def saveAndReportUser(def p) {
        p.passwordHash = ""
        def u
        if(ShiroUser.findByFacebookId(p?.facebookId)==null){
            u = new ShiroUser(p)
			u.addToRoles(ShiroRole.findByName(VendingConstance.ROLE_USER))
			u.save()
			if(u.hasErrors()){
				u.errors.each { println "eeee : ${it}" } 
			}else
				posterService.postResult(u.cardId)                
        }else
			u = ShiroUser.findByFacebookId(p.facebookId)
        return u
    }

	//TODO
	boolean isValidInfo(def json , def sign){
		//println sign
		return true
	}
	
	def gen = {
		if(params.cid!=null&&params.item!=null){
			new CsData(cid:params.cid,item:params.item).save(flush:true)
		}
	}
    def register = {        
        [redirectURL:"${ConfigurationHolder.config.grails.serverURL}/userProcess/registerFromFacebook".encodeAsURL()]
    }
    
    def p() {
    
        println " p - > params ${params}"
        def u = saveAndReportUser(params)
        
        render(contentType : "application/json") { 
            message= (u!=null) ? "success" : "fail"
            user=u?.id
        }
    }
}
